#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
from flask import Flask, request, jsonify, Response
import time

LOG_FILE_PATH = r"C:\Users\PC\Desktop\a.log"


app = Flask(__name__)

@app.route('/cmd', methods=['POST'])
def execute_cmd():
    data = request.get_json()
    if not data or 'command' not in data:
        return jsonify({'error': '缺少 command 参数'}), 400
    
    command = data['command']
    try:
        result = subprocess.run(command, shell=True, check=True, text=True, capture_output=True)
        return jsonify({
			'stdout': result.stdout,
            'stdout_pretty': result.stdout.replace('\n', '\r\n') if result.stdout else '',
            'stderr': result.stderr,
            'stderr_pretty': result.stderr.replace('\n', '\r\n') if result.stderr else '',
            'returncode': result.returncode
        })
    except subprocess.CalledProcessError as e:
        return jsonify({
            'stdout': e.stdout,
            'stdout_pretty': e.stdout.replace('\n', '\r\n') if e.stdout else '',
            'stderr': e.stderr,
            'stderr_pretty': e.stderr.replace('\n', '\r\n') if e.stderr else '',
            'returncode': e.returncode
        }), 500


def generate_log_lines():
    """生成器函数，不断读取新日志内容"""
    with open(LOG_FILE_PATH, 'r', encoding='utf-8') as f:
        # 先移动到文件末尾
        f.seek(0, 2)
        position = f.tell()
        count = 0
        while position >= 0 and count < 10:
            if position > 0:
                position -= 1
                f.seek(position)
            else:
                break
            if f.read(1) == '\n':
                count += 1
        f.seek(position + 1)  # 移动到第10行开头
        while True:
            line = f.readline()
            if not line:
                time.sleep(0.1)  # 等待新内容
                continue
            yield line

@app.route('/logs')
def stream_logs():
    """返回 chunked response，浏览器可实时接收新日志"""
    return Response(generate_log_lines(), mimetype='text/plain')
		
if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')